#include "Engine.h"

#include "States.h"
#include <iostream>
#include <pthread.h>
#include "ParrotNTarget.h"

#define PORT 57344

NetworkHandler *myHandler;
NetworkHandler *client;
NetworkHandler *server;

int main( int argc, char* argv[] )
{
	if ( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ) {
		std::cerr << "SDL initialization failed: "
			<< SDL_GetError() << std::endl;
		return false;
	}
	if(SDLNet_Init() == -1){
		std::cerr << "Unable to initialize networking.";
		exit(1);
	}
	
	bool isServer;
	bool hasDecided = 0;
	while(!hasDecided){
		std::cout << "Are you the server (y/n)? ";
		char res;
		std::cin >> res;
		if(res == 'y'){
			isServer = 1;
			hasDecided = 1;
		}
		else{
			if(res == 'n'){
				isServer = 0;
				hasDecided = 1;
			}
		}
	}
	
	if(isServer){
		NetworkServer *myServer = new NetworkServer(2,PORT);
		myHandler = myServer;
		server = myServer;
		client = new NetworkClient("localhost", PORT);
		std::cout << "Waiting for player.\n";
		while(myServer->getNumberOfConnections() <= 1){
			pthread_yield();
		}
		//std::cout << "Server wait loop ends.\n";
	}
	else{
		std::cout << "With whom do you want to play? ";
		char url[256];
		std::cin.width (254);
		std::cin >> url;
		NetworkClient *myClient = new NetworkClient(url, PORT);
		myHandler = myClient;
		client = myClient;
		server = NULL;
	}
	
	Engine e;

	if ( !e.init(0, server, client, isServer) ) return -1;

	e.push( Blank::Instance() );
	e.push( BulletState::Instance() );
	e.push( Assignment2::Instance() );

	e.run();

	e.cleanup();
	
	/*
	ParrotNTarget *chatTarget = new ParrotNTarget();
	myHandler->addTarget(0,chatTarget);
	
	char mssg[256];
	while(1){
		//if(isServer){
			std::cin.width (254);
			std::cin >> mssg;
			if ( 0 == strcmp( mssg, "quit" ) ) {
				exit(0);
			}
			myHandler->addBroadcastMessage(mssg, 256, 0);
			myHandler->broadcastMessages();
		//}
	}
	*/
	return 0;
}

